#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>

// 进行网络地址和主机地址之间的转换

class InetAddr
{
public:
    InetAddr(struct sockaddr_in &addr)
    {
        //网络转主机
        _addr = addr;
        _port = ntohs(addr.sin_port);
        // _ip = inet_ntoa(addr.sin_addr); // inet_ntoa接口返回的是一个字符串指针(inet_ntoa内部申请了一个共享区),是线程不安全的
        char ipbuff[64];
        inet_ntop(AF_INET, &addr.sin_addr, ipbuff, sizeof(ipbuff));
        _ip = ipbuff;
    }

    InetAddr(const std::string &ip, const uint16_t port)
        :_ip(ip),
         _port(port)
    {
        //主机转网络
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
        _addr.sin_port = htons(_port);
    }

    uint16_t Port() { return _port; }
    std::string Ip() { return _ip; }
    const struct sockaddr_in& NetAddr() { return _addr; }

    bool operator==(const InetAddr& addr)
    {
        return _ip == addr._ip && _port == addr._port;
    }
 
    std::string StringAddr()
    {
        return _ip + ":" + std::to_string(_port);
    }

    ~InetAddr(){}
private:
    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
};